<?php
/** 
 *  PHP Version 5
 *
 *  @category    Amazon
 *  @package     Amazon_EC2
 *  @copyright   Copyright 2008 Amazon Technologies, Inc.
 *  @link        http://aws.amazon.com
 *  @license     http://aws.amazon.com/apache2.0  Apache License, Version 2.0
 *  @version     2008-12-01
 */
/******************************************************************************* 
 *    __  _    _  ___ 
 *   (  )( \/\/ )/ __)
 *   /__\ \    / \__ \
 *  (_)(_) \/\/  (___/
 * 
 *  Amazon EC2 PHP5 Library
 *  Generated: Wed Dec 24 22:54:04 PST 2008
 * 
 */

    /**
    * This class represents S3 upload policy. Policy string
    * representaion and signature to be used within EC2 bundling API.
    */
    class Amazon_EC2_Util_S3UploadPolicy

    {
        private $_policySignature;
        private $_policyString;

        public function __construct(
            $awsAccessKeyId,
            $awsSecretKey,
            $bucketName,
            $prefix,
            $expireInMinutes = 1440)
        {
            $policy = "";
            $policy .= ("{");
            $policy .= ("\"expiration\": \"");
            $policy .= $this->_getFormattedTimestamp($expireInMinutes);
            $policy .= ("\",");
            $policy .= ("\"conditions\": [");
            $policy .= ("{\"bucket\": \"");
            $policy .= ($bucketName);
            $policy .= ("\"},");
            $policy .= ("{\"acl\": \"");
            $policy .= ("ec2-bundle-read");
            $policy .= ("\"},");
            $policy .= ("[\"starts-with\", \"\$key\", \"");
            $policy .= ($prefix);
            $policy .= ("\"]");
            $policy .= ("]}");
            $this->_policyString = base64_encode($policy);
            $this->_policySignature = base64_encode($this->_sign($this->_policyString, $awsSecretKey));
        }

        /**
         * Policy signature in base64 format
         * Use signature generated by this method
         * for passing to EC2 bunding calls along with policy.
         * @return Base64 signature
         */
        public function getPolicySignature() {
            return $this->_policySignature;
        }

        /**
         * Base64 representation of the serialized policy.
         * Use policy generated by this method
         * for passing to EC2 bunding calls.
         * @return Base64 policy
         */
        public function getPolicyString()
        {
            return $this->_policyString;

        }

        /**
         * Computes RFC 2104-compliant HMAC signature.
         */
        private function _sign($data, $key)
        {
            return
            hash_hmac('sha1', $data, $key, true);
        }


        /**
         * Formats date as ISO 8601 timestamp
         */
        private function _getFormattedTimestamp($expireInMinutes)
        {
            return gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", (time() + ($expireInMinutes * 60)));
        }


    }
